package com.powernode.bank.web;

import com.powernode.bank.execption.FailTransferExecption;
import com.powernode.bank.execption.MoneyNotEnoughExecption;
import com.powernode.bank.service.AccountService;
import com.powernode.bank.service.Impl.AccountServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * 转账的业务
 */
@WebServlet("/transfer")
public class AccountServlet extends HttpServlet {
    //为了让这个对象在其他方法中也可以使用，声明为示例变量
    private AccountService accountService = null;

    /**
     * Control层
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取前端页面传送过来的参数
        String fromActno = request.getParameter("fromActno");
        String toActno = request.getParameter("toActno");
        double money = Double.parseDouble(request.getParameter("money"));
        accountService = new AccountServiceImpl();
        try {
            //调用service的transfer方法进行转账（业务层）
            accountService.transfer(fromActno,toActno,money);
            //代码执行到这表示转账一定成功了
            //调用view完成页面展示
            response.sendRedirect(request.getContextPath() + "/success.html");
        } catch (MoneyNotEnoughExecption e) {
            response.sendRedirect(request.getContextPath() + "/error1.html");
        } catch (FailTransferExecption e) {
            response.sendRedirect(request.getContextPath() + "/error2.html");
        } catch (Exception e){
            response.sendRedirect(request.getContextPath() + "/error2.html");
        }
    }
}
